<template>
  <div
    id="divInput"
    contenteditable="true"
    class="tribute-demo-input"
    data-tribute="true"
    :value="inputText"
    @input="onInput"
  ></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from "vue";
import Tribute from "tributejs";
export interface Props {
  userList: User[];
}

type User = {
  name: string;
  id: string;
};
const props = withDefaults(defineProps<Props>(), {
  userList: () => [],
});

const copeList: any = ref([...props?.userList]);

const inputText = ref("");
let tribute = new Tribute({
  trigger: "@",
  values: props?.userList,
  lookup: "name",
  fillAttr: "id",
  selectClass: "highlight",
  requireLeadingSpace: false,
  selectTemplate: function (item) {
    copeList.value.forEach((i) => {
      if (i.id == item.original.id) {
        i.isSelected = true;
      }
    });
    return `<span class="highlighted" contenteditable="false">@${item.original.name}</span>`;
  },
});
const onInput = (e) => {
  inputText.value = e.target.innerText;
};
onMounted(() => {
  tribute.attach(document.getElementById("divInput"));
});

onBeforeUnmount(() => {
  tribute.detach(document.getElementById("divInput"));
});

const atUserList = computed(() => {
  const list = [];
  copeList.value.forEach((i) => {
    if (i.isSelected && inputText.value.includes(i.name)) {
      list.push(
        i.map((c) => {
          return {
            name: c.name,
            id: c.id,
          };
        })
      );
    }
  });
  return list;
});
defineExpose({
  atUserList,
});
// function getAtUserId('sdaf@张三sadsf@李四'){

// }
</script>

<style lang="scss">
.highlight {
  background: rgb(235, 243, 255);
  color: #85b0ff;
}
/* 这是外部的容器样式 */
.tribute-container {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #fff;
  color: #2c3e50;
  max-height: 280px;
  overflow: auto;
  z-index: 1000; /*保证在其他元素之上*/
}
.tribute-container ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}
/* 这是每一个列表项的样式 */
.tribute-container li {
  box-sizing: border-box;
  padding: 4px 20px;
  cursor: pointer;
  transition: all 0.3s;
}
.highlighted {
  color: #85b0ff; /* 你也可以将这个颜色设定为你想要的任何颜色 */
}

#divInput {
  width: 200px;
  height: auto;
  border: 1px solid #d8dae2;
  padding: 5px;
}
.tribute-demo-input {
  outline: none;
  /* outline: 1px solid red; */
  /* border: 1px solid #eee; */
  padding: 3px 5px;
  border-radius: 2px;
  font-size: 15px;
  min-height: 32px;
  cursor: text;
  &:focus {
    outline: 1px solid #85b0ff;
  }
}
</style>
